﻿using System;
using System.Collections.Generic;

namespace Protocol.Dto
{
    /// <summary>
    /// 房间数据对应的数据模型
    /// </summary>
    [Serializable]
    public class MatchRoomDto
    {
        /// <summary>
        /// 用户id对应的用户数据的传输模型
        /// </summary>
        public Dictionary<int, UserDto> UIdUserDict;

        /// <summary>
        /// 准备的玩家id列表
        /// </summary>
        public List<int> ReadyUIdList;

        /// <summary>
        /// 存储玩家进入的顺序
        /// </summary>
        public List<int> UIdList;

        public MatchRoomDto()
        {
            this.UIdUserDict = new Dictionary<int, UserDto>();
            this.ReadyUIdList = new List<int>();
            this.UIdList = new List<int>();
        }

        public void Add(UserDto newUser)
        {
            UIdUserDict.Add(newUser.Id, newUser);
            this.UIdList.Add(newUser.Id);
        }


        public void Leave(int userId)
        {
            this.UIdUserDict.Remove(userId);
            this.UIdList.Remove(userId);
        }

        public void Ready(int userId)
        {
            this.ReadyUIdList.Add(userId);
        }

        /// <summary>
        /// 左边玩家的id
        /// </summary>
        public int LeftId;

        /// <summary>
        /// 右边玩家的id
        /// </summary>
        public int RightId;

        /// <summary>
        /// 重置位置
        /// 在玩家进入 或者 离开 房间时都需要调整位置
        /// </summary>
        public void ResetPosition(int myUserId)
        {
            LeftId = -1;
            RightId = -1;

            switch (UIdList.Count)
            {
                case 1:
                    return; // 房间只有自己不用操作
                case 2:
                {
                    // 自己第一个进入房间
                    if (UIdList[0] == myUserId)
                    {
                        RightId = UIdList[1];
                    }

                    // 自己第2个进入房间
                    if (UIdList[1] == myUserId)
                    {
                        LeftId = UIdList[0];
                    }

                    break;
                }
                case 3:
                {
                    // x a b
                    if (UIdList[0] == myUserId)
                    {
                        LeftId = UIdList[2];
                        RightId = UIdList[1];
                    }

                    // a x b
                    if (UIdList[1] == myUserId)
                    {
                        LeftId = UIdList[0];
                        RightId = UIdList[2];
                    }

                    // a b x
                    if (UIdList[2] == myUserId)
                    {
                        LeftId = UIdList[1];
                        RightId = UIdList[0];
                    }

                    break;
                }
                default:
                    Console.WriteLine("Something Logic Wrong");
                    break;
            }
        }
    }
}